<template>
  <div class="password-input">
    <!-- 4个密码输入框 -->
    <input
      v-for="(input, index) in inputs"
      :key="index"
      type="password"
      maxlength="1"
      v-model="inputValues[index]"
      @keydown="handleKeyDown(index, $event)"
      ref="inputsRef"
      class="password-input-box"
      :disabled="isDisabled"
      :auto-focus="index === 0"
    />
  </div>
</template>

<script>
import { ref, watch } from "vue";

export default {
  name: "PasswordInput",
  props: {
    modelValue: {
      type: String,
      required: true
    },
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const inputValues = ref(["", "", "", ""]); // 用于存储4个输入框的值
    const inputsRef = ref([]); // 用于存储每个输入框的引用

    // 监听密码值变化
    watch(
      () => props.modelValue,
      newValue => {
        inputValues.value = newValue.split("");
      }
    );

    // 处理键盘事件
    const handleKeyDown = (index, event) => {
      const input = event.target;
      const maxLength = parseInt(input.getAttribute("maxlength"));

      // 输入框已满并且按下的键不是 Backspace 时，自动跳到下一个输入框
      if (input.value.length >= maxLength) {
        if (event.key !== "Backspace" && index < 3) {
          event.preventDefault();
          inputsRef.value[index + 1].focus();
        }
      }

      // 处理 Backspace 键
      if (event.key === "Backspace" && input.value === "") {
        if (index > 0) {
          inputValues.value[index - 1] = "";
          emit("update:modelValue", inputValues.value.join(""));
          inputsRef.value[index - 1].focus();
        }
      }

      // 实时更新密码值
      if (event.key !== "Backspace") {
        inputValues.value[index] = input.value;
        emit("update:modelValue", inputValues.value.join(""));
      }
    };

    return {
      inputValues,
      inputsRef,
      handleKeyDown
    };
  }
};
</script>

<style scoped>
.password-input {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.password-input-box {
  width: 40px;
  height: 40px;
  text-align: center;
  font-size: 18px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.password-input-box:focus {
  border-color: #4d90fe;
  outline: none;
}
</style>
